<script setup>
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { reactive, onMounted, ref, toRaw ,watch} from 'vue'
import useFileUpload from "@/utiles/common.js";


defineOptions({
  name: 'RichTextEditor'
})

const props = defineProps({
  modelValue: String
})
const emit = defineEmits(['update:modelValue']) // 改为标准v-model事件


const myQuillEditor = ref()
const fileBtn = ref()
const data = reactive({
  content: '',
  editorOption: {
    modules: {
      toolbar: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'header': 1 }, { 'header': 2 }],
        ['image'],
      ]
    },
    placeholder: '请输入内容...'
  }
})
const imgHandler = (state) => {
  if (state) {
    fileBtn.value.click()
  }
}
const setValue = () => {
  const text = toRaw(myQuillEditor.value).getHTML()
  emit('update:modelValue', text)
}

watch(
  () => props.modelValue,
  (newVal) => {
    if (myQuillEditor.value && newVal !== myQuillEditor.value.getHTML()) {
      console.log("..."+newVal)
      myQuillEditor.value.setHTML(newVal)
    }
  },
  { immediate: true }
)

const imgUpload = useFileUpload({
  endpoint: 'http://localhost:8081/common/upload',
  extraData: {type: 'post'}, // 告诉后端这是头像
  maxSize: 2 * 1024 * 1024,     // 图片限制2MB
  allowedTypes: ['image/jpeg', 'image/png', 'image/jpg']
})
const handleUpload = async (e) => {
  const file = e.target.files[0]
  if (!file) {
    return
  }
  let url = null
  try {
    url = await imgUpload.upload(file)
    console.log(url)
  } catch {
    console.log("上传错误")
  }

  const quill = toRaw(myQuillEditor.value).getQuill()
  const length = quill.getSelection().index
  // 插入图片，res为服务器返回的图片链接地址
  quill.insertEmbed(length, 'image', url)
  // 调整光标到最后
  quill.setSelection(length + 1)
}
onMounted(() => {
  const quill = toRaw(myQuillEditor.value).getQuill()
  if (myQuillEditor.value) {
    quill.getModule('toolbar').addHandler('image', imgHandler)
  }
  toRaw(myQuillEditor.value).setHTML(props.modelValue)
})
</script>

<template>
  <div>
    <QuillEditor ref="myQuillEditor"
                 theme="snow"
                 :content="modelValue"
                 :options="data.editorOption"
                 contentType="html"
                 @update:content="setValue()"
    />
    <!-- 使用自定义图片上传 -->
    <input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleUpload" />
  </div>
</template>


<style scoped lang="scss">
:deep(.ql-editor) {
  min-height: 180px;
}
:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}
</style>
